﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Beway.ValueAdded.Service;
using Beway.ValueAdded.Model;
using Beway.ValueAdded.Model.ViewModel;

namespace Beway.ValueAdded.Admin.Controllers
{
    public class RechargeController : BaseController
    {
        //
        // GET: /Recharge/

        RechargeServ Service = SingletonProvider<RechargeServ>.Instance;
        AdminUserServ admSvc = SingletonProvider<AdminUserServ>.Instance;
        ReUserServ ruServ = SingletonProvider<ReUserServ>.Instance;
        public ActionResult List()
        {          
            var q = ruServ.SelectAll().Where(m=>m.RechStatus==1); //过滤禁用的用户
            int adminId = 0;
            if (CurrentRole == ManagerRoleType.MerchantAdmin)
            {
                adminId = admSvc.GetByUserName(User.Identity.Name).AdminID;
                if (adminId > 0)
                {
                    q = q.Where(m => m.AdminId == adminId).ToList();
                }
            }

            ViewBag.ReUserList = q;
            return View();
        }


        public JsonResult RechargeList(int? page, int? rows, int? userId, string orderNo, string rcTarget, DateTime? beginTime, DateTime? endTime, int rcStatus = -1)
        {
            int ListCount = 0;
            int adminId = 0;
            if (CurrentRole == ManagerRoleType.MerchantAdmin)
            {
                adminId = admSvc.GetByUserName(User.Identity.Name).AdminID;
            }

            var d = Service.RechargeList(page ?? 0, rows ?? 0, userId??0, adminId, orderNo,rcTarget,rcStatus,beginTime,endTime, out ListCount);
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", ListCount);
            json.Add("rows", d);
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        //导出
        [HttpPost]
        public ActionResult Export(int? userId, string orderNo, string rcTarget, DateTime? beginTime,DateTime? endTime, int rcStatus = -1)
        {
            int ListCount = 0;
            int adminId = 0;
            if (CurrentRole == ManagerRoleType.MerchantAdmin)
            {
                adminId = admSvc.GetByUserName(User.Identity.Name).AdminID;
            }
            var list = Service.RechargeList(1, 100000000, userId ?? 0, adminId,orderNo, rcTarget, rcStatus, beginTime,endTime, out ListCount);
            string filename = "re" + beway.common.FileUtil.GetFileNameFromSystemAuto();
            return new beway.common.ExcelResult<RechargeView>(list, filename);
        }

        /// <summary>
        /// 补充充值
        /// </summary>
        /// <param name="rcId">充值ID</param>
        /// <returns></returns>
        public JsonResult RechargeAgain(int rcId)
        {
            bool blnRet = false;
            string strMsg = "";
            Recharge re = Service.GetById(rcId);
            if (re != null && re.RCID > 0 && re.RechargeStatus!=1)
            {
                //生成新的订单号，欧飞平台不允许重复
                string orderID = "RE" + beway.common.FileUtil.GetFileNameFromSystemAuto() + re.UserID.ToString();
                re.OrderID = orderID;                

                //调用充值接口
                if (re.RCType < 3) //1话费，2q币
                {
                    int reRet = 0;
                    ReUser reuser = new ReUser
                    {
                        RechDiscountRate = 0
                    };
                    string strRet = Service.RechargeTrade(re, reuser); //0系统异常，1成功，2充值中，3充值失败，可以退款          

                    int.TryParse(strRet, out reRet);

                    if (reRet == 1)//1成功
                    {
                        blnRet = true;
                        strMsg = "补充充值成功！";

                        re.RechargeStatus = 1;
                        re.RechargeSuccessTime = System.DateTime.Now;

                    }
                    else if (reRet == 2)//2充值中，
                    {
                        blnRet = true;
                        strMsg = "充值中，请稍后查询充值结果（充值结果未返回前，请不要再次补充！)";
                    }
                    else if (reRet == 3)//3充值失败，可以退款，欧飞返回状态码为9 
                    {
                        strMsg = "充值失败，请稍后重试(供应商原因)!";
                    }
                    else
                    {
                        strMsg = re.RechargeErrorReason;//记录充值实时返回的错误
                    }

                    re.RechargeErrorReason = strMsg;
                }
                else //礼品卡类
                {
                    //调用提卡接口
                    if (Service.GiftCardTrade(re))
                    {
                        blnRet = true;
                        strMsg = "提卡成功，请将卡号及密码发送客户(注意保密)。";
                    }
                    else
                    {
                        strMsg = "提卡失败，请查看失败原因或联系技术人员查询日志。";
                    }                                  
                }
                //更新充值结果
                bool isUpdate = Service.Update(re);             
            }
            else
            {
                strMsg = "抱歉！此记录状态已发生变化，请刷新后重试。";
            }

            return Json(new { msg = strMsg, ret = blnRet }, JsonRequestBehavior.AllowGet);        
        }       
    }
}
